from django.shortcuts import render
from django.http import HttpResponse
from .models import VideoSuffix,Role,VideoLabel,Video,VideoPath
import sys
import os,shutil
#处理文件目录等相关信息最好引用Pathlib模块
from pathlib import Path
from .common import *
import re

#读取文本
def reafTxt(file,mode = "r"):
    new_lines = []
    with open(file,mode) as f:
        lines = f.readlines()
        #去掉换行符
        if lines:
            for line in lines:
                new_lines.append(line.strip("\n"))
    f.close()
    return new_lines

#更新收录的视频格式
def upsuffix(suffix):
    #视频格式
    vs = ['mp4','avi','wmv','mov','rmvb','mkv','mpeg','3gp','flv','f4v','mpg']

    suffix = suffix.lower()
    
    #视频格式,先检查数据库
    video_suf = VideoSuffix.objects.filter(name=suffix).first()

    if video_suf:
        suffix_id = video_suf.suffix_id
        return suffix_id
    elif suffix in vs:
        videoSuffix = VideoSuffix(name=suffix)
        videoSuffix.save()
        suffix_id = videoSuffix.suffix_id
        return suffix_id
    else:
        return False

#演员收录或更新,cname中文名,rname真名
def uprole(path,cname,area,rname = ''):
    #判断名字是否是英文,英文名字首字母大写处理
    #检验是否含有中文字符
    if not is_contains_chinese(cname):
        cname = cname.title()
        rname = cname

    #曾用名
    oname = ''
    #判断名字中是否包含(***)的旧名,"("又分为中英文
    if "(" in cname:
        arr = cname.split('(',1)
        cname = arr[0]
        oname = arr[1].strip(')')

    if "（" in cname:
        arr = cname.split('（',1)
        cname = arr[0]
        oname = arr[1].strip('）')

    #先检查数据库中是否有已存在信息
    result = Role.objects.filter(chinese_name=cname).first()
    #没有则新增
    if not result:
        #检查图片是否存在
        img = rolePhoto(None,cname,rname,oname,area)
        role = Role(chinese_name=cname,real_name=rname,old_names=oname,photo=img,path=path,area=area)
        role.save()
        role_id = role.role_id
    else:
        role_id = result.role_id
    
    return role_id

#组合并判断图片文件是否存在
def photo_file(path,c_jpg,r_jpg,o_jpg):
    c_img = Path(path).joinpath(c_jpg)
    r_img = Path(path).joinpath(r_jpg)
    o_img = Path(path).joinpath(o_jpg)
    img = ''
    if c_img.is_file():
        img = c_img
    elif r_img.is_file():
        img = r_img
    elif o_img.is_file():
        img = o_img
    return img

#获取演员图片地址
def rolePhoto(role_id = None,cname = None,rname = None,oname = None,area = None):
    #根据地区获取演员图片地址
    dir = Path(__file__).resolve().parent
    txt_path = Path(dir).joinpath('photo_path.txt')
    #判断文件是否存在
    if txt_path.exists():
        content = reafTxt(txt_path)
    else:
        return False 
    
    #如果role_id不为空，则根据role_id去数据表中获取信息
    #这里有两种情况，传role_id表示数据表中已存在数据，在这里需要修改；传其它参数表示是新增，只需要返回图片路径即可
    if role_id is not None:
        role_info = Role.objects.filter(role_id=role_id).first()
        if role_info:
            cname = role_info.chinese_name
            rname = role_info.real_name
            oname = role_info.old_names
            area  = role_info.area

    c_jpg = "{}.{}".format(cname,'jpg')
    r_jpg = "{}.{}".format(rname,'jpg')
    o_jpg = "{}.{}".format(oname,'jpg')
    
    if len(content) > 0:
        for i in content:
            #根据area来使用图片文件路径
            if area == 1 and '日本' in i:
                #组合路径和图片名称,再判断文件是否存在，最后更新数据库
                img = photo_file(i,c_jpg,r_jpg,o_jpg)
            elif area == 2 and '欧美' in i:
                img = photo_file(i,c_jpg,r_jpg,o_jpg)
            elif area == 3 and '韩国' in i:
                img = photo_file(i,c_jpg,r_jpg,o_jpg)
            elif area == 4 and '中国香港' in i:
                img = photo_file(i,c_jpg,r_jpg,o_jpg)
            elif area == 5 and '中国' in i:
                img = photo_file(i,c_jpg,r_jpg,o_jpg)
        #更新数据库或返回图片地址
        if role_id is not None:
            Role.objects.filter(role_id=role_id).update(photo=img)
        else:
            return img

#处理文件名，并修改文件的名字
def repairName(file):
    print('file:',file)
    #判断文件是否存在
    p = Path(file)
    if not p.is_file():
        return False
    #获取文件名与格式
    file_name = p.stem  #文件名
    file_suffix = p.suffix #后缀
    #获取不带.的后缀
    file_suffix = file_suffix.lstrip('.')
    #获取父文件夹名
    parent_dir = p.parent

    #处理文件名中的特殊符号之间的内容
    #file_name = clearContentWithSpecialCharacter(file_name)
    arr = ['【ses23.com】','[Thz.la]','[ThZu.Cc]','(www.overdays.com)']
    for i in arr:
        if i in file_name:
            file_name = file_name.replace(i,'')
    
    #获取字母
    fanhao_z_list = re.findall(r'[A-Za-z]', file_name)
    fanhao_z = ''.join(fanhao_z_list)
    #字母大写
    fanhao_z = fanhao_z.upper()
    #获取数字
    fanhao_s = re.sub("\D", "", file_name)
    #拼组fh
    #fanhao = "{}-{}".format(fanhao_z,fanhao_s)

    #判断是否有码
    if '无码' in file_name:
        mosaic = 0
    else:
        mosaic = 1

    #将名字中的字母全部转为大写，并修改文件名
    srcFile = file
    new_file = "{}.{}".format(file_name.upper(),file_suffix)
    dstFile = parent_dir.joinpath(new_file)

    #判断是否有中文字幕
    if '-C' in new_file:
        subtitle = 1
    else:
        subtitle = 0

    #更新获取suffix_id
    suf = upsuffix(file_suffix)

    if suf:
        suffix_id = suf
    else:
        suffix_id = 0

    #是否开启修改文件名
    pflag = True
    if pflag:
        try:
            os.rename(srcFile,dstFile)
        except Exception as e:
            print(e)
            print('rename file fail\r\n')
        else:
            print('rename file success\r\n')

    result = {'designation':fanhao_z,'designation_name':fanhao_s,'name':file_name,'mosaic':mosaic,'subtitle':subtitle,'newFile':dstFile,'suffix_id':suffix_id,'suffix':file_suffix}
    return result

#录入video和video_path wuma:0无码，1有码 用于日本
def saveVideoAndPath(file,role_id,wuma=1):
    #文件
    info = repairName(file)
    #判断文件是否是视频类文件，只有视频类文件才记录
    suffix_id = info['suffix_id']
    if suffix_id > 0:
        designation = info['designation']
        designation_name = info['designation_name']
        name = info['name']
        mosaic = info['mosaic']
        if wuma == 0:
            mosaic = wuma
        subtitle = info['subtitle']
        newFile = info['newFile']
        suffix_id = info['suffix_id']
        #先检查数据库中是否已存在数据
        check = Video.objects.filter(designation=designation,designation_name=designation_name).first()
        if not check:
            #不存在则新增
            videoModel = Video(role_id=role_id,designation=designation,designation_name=designation_name,name=name,mosaic=mosaic,subtitle=subtitle,suffix_id=suffix_id)
            videoModel.save()
            video_id = videoModel.id

            videoPathModel = VideoPath(video_id=video_id,name=name,path=newFile,suffix_id=suffix_id,role_id=role_id)
            videoPathModel.save()
            return True
    return False
#用于日本
def saveVideoAndPath2(file,role_id,fanhao_z,fanhao_s,fanhao,wuma=1):
    #文件
    info = repairName(file)
    #判断文件是否是视频类文件，只有视频类文件才记录
    suffix_id = info['suffix_id']
    if suffix_id > 0:
        name = info['name']
        mosaic = info['mosaic']
        if wuma == 0:
            mosaic = wuma
        subtitle = info['subtitle']
        newFile = info['newFile']
        suffix_id = info['suffix_id']
        #先检查数据库中是否已存在数据
        check = Video.objects.filter(designation=fanhao_z,designation_name=fanhao_s).first()
        if not check:
            #不存在则新增
            videoModel = Video(role_id=role_id,designation=fanhao_z,designation_name=fanhao_s,name=fanhao,mosaic=mosaic,subtitle=subtitle,suffix_id=suffix_id)
            videoModel.save()
            video_id = videoModel.id
        else:
            video_id = check.id

        #检查文件夹下的所有文件是否已记录，没有则新增
        check_video_path = VideoPath.objects.filter(video_id=video_id,name=name).first()
        if not check_video_path:
            videoPathModel = VideoPath(video_id=video_id,name=name,path=newFile,suffix_id=suffix_id,role_id=role_id)
            videoPathModel.save()
            return True
    return False

#用于欧美
def saveAmeric(file,role_id):
    #判断文件是否存在
    p = Path(file)
    if not p.is_file():
        return False
    #获取文件名与格式
    file_name = p.stem  #文件名
    file_suffix = p.suffix #后缀
    #获取不带.的后缀
    file_suffix = file_suffix.lstrip('.')
    #更新获取suffix_id
    suf = upsuffix(file_suffix)

    if suf:
        suffix_id = suf
    else:
        suffix_id = 0
    #先检查数据库中是否已存在数据
    check = Video.objects.filter(name=file_name).first()
    if not check:
        #不存在则新增
        videoModel = Video(role_id=role_id,name=file_name,mosaic=0,suffix_id=suffix_id)
        videoModel.save()
        video_id = videoModel.id

        videoPathModel = VideoPath(video_id=video_id,name=file_name,path=file,suffix_id=suffix_id,role_id=role_id)
        videoPathModel.save()
        return True
    return False
#更新演员收录视频数量
def upRoleVideoNum(role_id=None):
    if role_id is None:
        #全部检查更新
        role_info = Role.objects.filter(is_del=0)
        if role_info:
            for i in role_info:
                role_id = i.role_id
                check_fanhao_num = Video.objects.filter(role_id=role_id).count()
                check_video_num = VideoPath.objects.filter(role_id=role_id).count()
                Role.objects.filter(role_id=role_id).update(include_fanhao=check_fanhao_num,include_number=check_video_num)
    else:
        check_fanhao_num = Video.objects.filter(role_id=role_id).count()
        check_video_num = VideoPath.objects.filter(role_id=role_id).count()
        Role.objects.filter(role_id=role_id).update(include_fanhao=check_fanhao_num,include_number=check_video_num)


#检索视频资源
def retrieval():
    #读取检索资源地址
    dir = Path(__file__).resolve().parent
    txt_path = Path(dir).joinpath('research_path.txt')
    #判断文件是否存在
    if txt_path.exists():
        content = reafTxt(txt_path)
    else:
        return False
    
    role_num = 0
    video_num = 0
    if len(content) > 0:
        for i in content:
            if len(i.strip()) > 0:
                #文件名中包含有“欧美”的地区名也是“欧美”
                if "欧美" in i:
                    area = 2
                elif "韩国" in i:
                    area = 3
                elif "香港" in i:
                    area = 4
                elif "中国" in i:
                    area = 5
                else:
                    area = 1
                #这里有两种情况，1知道演员名字，2未知演员或还未收录演员
                #先检查"未知"的信息是否录入，未录入则新增

                role_names_path = Path(i).glob('*')
                
                if role_names_path:
                    #排序
                    arr = []
                    for m in role_names_path:
                        arr.append(m)
                    arr.sort()
                    for role_name_path in arr:
                        #获取演员名,目录的名称才是演员名
                        if Path(role_name_path).is_dir():
                            role_name = role_name_path.name
                            #收录演员
                            role_id = uprole(role_name_path,role_name,area)
                            role_num += 1
                            #获取目录下的所有文件及文件夹,这里要判断是文件还是文件夹，因为一个视频可能分为几个并存于一个文件夹内
                            files = Path(role_name_path).glob('*')
                            if files:
                                for file in files:
                                    if file.is_file():
                                        #判断日韩欧美
                                        if area == 1:
                                            lu = saveVideoAndPath(file,role_id)
                                        elif area == 2:
                                            lu = saveAmeric(file,role_id)
                                        if lu:
                                            video_num += 1
                                    elif file.is_dir():
                                        z_files = Path(file).glob('*')
                                        #如果是空文件夹，不作记录
                                        if z_files:
                                            #文件夹,判断文件名是否全是中文,全是中文的只有"无码"类自建文件夹
                                            f_name = file.name
                                            if is_all_chinese(f_name) and '无码' in f_name:
                                                #“无码”类文件夹下可能还有文件夹
                                                for z in z_files:
                                                    if z.is_file():
                                                        wuma = 0
                                                        #判断日韩欧美
                                                        if area == 1:
                                                            lu = saveVideoAndPath(file,role_id,wuma)
                                                        elif area == 2:
                                                            lu = saveAmeric(file,role_id)
                                                        if lu:
                                                            video_num += 1
                                                    elif z.is_dir():
                                                        zz = Path(z).glob('*')
                                                        fanhao = z.name.upper()
                                                        #获取字母
                                                        fanhao_z_list = re.findall(r'[A-Za-z]', fanhao)
                                                        fanhao_z = ''.join(fanhao_z_list)
                                                        #获取数字
                                                        fanhao_s = re.sub("\D", "", fanhao)
                                                        for xf in zz:
                                                            if xf.is_file():
                                                                #判断日韩欧美
                                                                if area == 1:
                                                                    lu = saveVideoAndPath2(xf,role_id,fanhao_z,fanhao_s,fanhao,0)
                                                                elif area == 2:
                                                                    lu = saveAmeric(file,role_id)
                                                                
                                                                if lu:
                                                                    video_num += 1
                                            else:
                                                #非全中文，表示文件夹的名称很可能就是番号
                                                fanhao = f_name.upper()
                                                #获取字母
                                                fanhao_z_list = re.findall(r'[A-Za-z]', fanhao)
                                                fanhao_z = ''.join(fanhao_z_list)
                                                #字母大写
                                                #fanhao_z = fanhao_z.upper()
                                                #获取数字
                                                fanhao_s = re.sub("\D", "", fanhao)
                                                for zf in z_files:
                                                    if zf.is_file():
                                                        #判断日韩欧美
                                                        if area == 1:
                                                            lu = saveVideoAndPath2(zf,role_id,fanhao_z,fanhao_s,fanhao)
                                                        elif area == 2:
                                                            lu = saveAmeric(file,role_id)
                                                        
                                                        if lu:
                                                            video_num += 1
                            #更新演员视频收录记录
                            upRoleVideoNum(role_id)

    return content

def index(request):
    res = retrieval()
    print(res)
    return HttpResponse(res)

